package com.honkentuber.chat;

import org.json.simple.JSONObject;

import com.google.appengine.api.datastore.KeyFactory;
import com.honkentuber.AppContext;

public class DeleteRoomServlet extends ChatBaseServlet {
  private static final long serialVersionUID = -3077393916594087841L;

  private static String deleteRoom(AppContext ctx) {
    String response = "";
    try {
      long count = 0;
      String key = ctx.req.getParameter("key");
      if (key != null && key.length() > 0) {
        ChatContext chatCtx = (ChatContext) ctx;
        ChatDatabase db = chatCtx.getChatDb();
        count = db.deleteRoom(KeyFactory.stringToKey(key));
      }
      response = count >= 0
          ? ("Deleted " + key + " and " + count + " messages")
          : ("Room not found");
    } catch (NumberFormatException ex) {
      response = ex.getMessage();
    }
    return response;
  }

  @Override
  protected String newJspResponse(AppContext ctx) {
    String response = deleteRoom(ctx);
    ctx.req.setAttribute("response", response);
    return "/response.jsp";
  }

  @Override
  @SuppressWarnings("unchecked")
  protected JSONObject newJsonResponse(AppContext ctx) {
    String response = deleteRoom(ctx);
    JSONObject jsonResponse = new JSONObject();
    jsonResponse.put("response", response);
    return jsonResponse;
  }
}